﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sern.Abstracts.Common;
using Sern.Common;

namespace Sern.ServiceImplementation.MapReduce
{
    public static class KeyHelper
    {
        public static Guid GetKeyHash(this object key)
        {
            var isSelfHealingKey = IsSelfHealingKey(key);
            return isSelfHealingKey
                       ? ObjectHasher.GetHashGuid(((dynamic) key).Key)
                       : ObjectHasher.GetHashGuid(key);

        }

        public static Guid GetRedundancyKeyHash(this object key)
        {
            var isSelfHealingKey = IsSelfHealingKey(key);
            return isSelfHealingKey &&
                    ((dynamic)key).RedundancyKeys != null &&
                    ((dynamic)key).RedundancyKeys.Count > 0
                       ? ObjectHasher.GetHashGuidFromEnumerable(((dynamic)key).RedundancyKeys)
                       : ObjectHasher.GetHashGuid(key);
        }

        public static bool IsSelfHealingKey(this object key)
        {
            Type keyType = key.GetType();
            bool isSelfHealingKeyFound = false;
            do
            {
                isSelfHealingKeyFound = keyType.FullName.StartsWith(typeof (SelfHealingKey<>).FullName);
            } while (!isSelfHealingKeyFound && (keyType = keyType.BaseType) != typeof (object));
            return isSelfHealingKeyFound;
        }
    }
}
